package com.atguigu.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.atguigu.constant.MessageConstant;
import com.atguigu.dao.TravelGroupDao;
import com.atguigu.entity.PageResult;
import com.atguigu.entity.QueryPageBean;
import com.atguigu.entity.Result;
import com.atguigu.pojo.TravelGroup;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = TravelGroupService.class)
@Transactional
public class TravelGroupServiceImpl implements TravelGroupService {

    @Autowired
    private TravelGroupDao travelGroupDao;

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page page = travelGroupDao.findPageByQueryString(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Result addGroup(TravelGroup travelGroup, Integer[] travelItemIds) {
        travelGroupDao.addGroup(travelGroup);
        this.addById(travelGroup.getId(),travelItemIds);
        return new Result(true, MessageConstant.ADD_TRAVELGROUP_SUCCESS);
    }
    public void addById(Integer travelGroup ,Integer[] travelItemIds){
        for (Integer travelItemId : travelItemIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("travelGroup",travelGroup);
            map.put("travelItem",travelItemId);
            travelGroupDao.addGroupAndItemById(map);
        }

    }
    @Override
    public TravelGroup findById(Integer id) {
        return travelGroupDao.findById(id);
    }

    @Override
    public List<Integer> findTravelItemIdByTravelgroupId(Integer id) {
        return travelGroupDao.findTravelItemIdByTravelgroupId(id);
    }

    @Override
    public void edit(Integer[] travelItemIds, TravelGroup travelGroup) {
        travelGroupDao.edit(travelGroup);
        travelGroupDao.deleteTravelGroupAndTravelItemByTravelGroupId(travelGroup.getId());
        this.addById(travelGroup.getId(),travelItemIds);
    }

    @Override
    public void deleteById(Integer id) {
        List<Integer> travelItemIds = travelGroupDao.findTravelItemIdByTravelgroupId(id);
        if (travelItemIds==null||travelItemIds.size()==0){
            travelGroupDao.deleteById(id);
        }else{
            throw  new RuntimeException("不允许删除!!");
        }
    }

    @Override
    public List<TravelGroup> findAll() {
        return travelGroupDao.findAll();
    }
}
